<template>
  <div class="good">
    <div class="mybody">
      <!-- 标题和新增按钮 -->
      <div class="header">
        <el-button type="success" @click="handleAdd">新增轮播图</el-button>
      </div>

      <!-- 表单 -->
      <el-form class="mytable">
        <el-table :data="carouselList" border stripe style="width: 100%" ref="tableRef" align="center" v-loading="loading">
          <el-table-column label="ID" width="80" prop="id" align="center" />
          <el-table-column label="商品ID" width="100" prop="goodId" align="center" />
          <el-table-column label="商品名称" prop="goodName" align="center" />
          <el-table-column label="商品图片" align="center">
            <template #default="scope">
              <img :src="`http://localhost:9191${scope.row.img}`" width="80" height="80">
            </template>
          </el-table-column>
          <el-table-column label="显示顺序" width="100" prop="showOrder" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="50%"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="商品ID" prop="goodId">
          <el-select v-model="form.goodId" placeholder="请选择商品" filterable>
            <el-option
              v-for="good in goodsList"
              :key="good.id"
              :label="good.name"
              :value="good.id"
            >
              <div style="display: flex; align-items: center;">
                <img :src="`http://localhost:9191${good.imgs}`" style="width: 30px; height: 30px; margin-right: 10px;">
                <span>{{ good.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="showOrder">
          <el-input-number v-model="form.showOrder" :min="1" :step="1"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, inject } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 注入axios
const $axios = inject('$axios');

// 数据定义
const carouselList = ref([]);
const goodsList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('新增轮播图');
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: null,
  goodId: null,
  showOrder: 1
});

// 表单验证规则
const rules = reactive({
  goodId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  showOrder: [
    { required: true, message: '请输入显示顺序', trigger: 'blur' }
  ]
});

// 获取所有轮播图
const fetchCarousels = async () => {
  loading.value = true;
  try {
    const response = await $axios.get('/api/carousel');
    if (response.code === '200') {
      carouselList.value = response.data;
    } else {
      ElMessage.error('获取轮播图列表失败');
    }
  } catch (error) {
    console.error('获取轮播图列表出错:', error);
    ElMessage.error('获取轮播图列表出错');
  } finally {
    loading.value = false;
  }
};

// 获取所有商品
const fetchGoods = async () => {
  try {
    const response = await $axios.get('/api/good');
    if (response.code === '200') {
      goodsList.value = response.data;
    } else {
      ElMessage.error('获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表出错:', error);
    ElMessage.error('获取商品列表出错');
  }
};

// 新增轮播图
const handleAdd = () => {
  form.id = null;
  form.goodId = null;
  form.showOrder = 1;
  if (formRef.value) {
    formRef.value.resetFields();
  }
  dialogTitle.value = '新增轮播图';
  dialogVisible.value = true;
};

// 编辑轮播图
const handleEdit = (row) => {
  form.id = row.id;
  form.goodId = row.goodId;
  form.showOrder = row.showOrder;
  dialogTitle.value = '编辑轮播图';
  dialogVisible.value = true;
};

// 删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await $axios.delete(`/api/carousel/${row.id}`);
      if (response.code === '200') {
        ElMessage.success('删除成功');
        fetchCarousels();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除轮播图出错:', error);
      ElMessage.error('删除轮播图出错');
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除操作');
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    let url = '/api/carousel';
    let method = form.id ? 'put' : 'post';
    
    const response = await $axios[method](url, form);
    
    if (response.code === '200') {
      ElMessage.success(form.id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      // 清空表单数据
      form.id = null;
      form.goodId = null;
      form.showOrder = 1;
      fetchCarousels();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('提交表单出错');
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchCarousels();
  fetchGoods();
});
</script>

<style scoped>
.good {
  padding: 30px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.mybody {
  width: 100%;
  padding: 0;
}

.header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}

.mytable {
  text-align: center;
  width: 100%;
}

/* 按钮样式 */
.good .mytable :deep(button>span) {
  color: white;
  font-family: "黑体";
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-form) {
  width: 100%;
  margin: 0;
  padding: 0;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>